$(function(){
    var banner = $('#banner');
    var buttons = $('#slide-btns');
    var list = $('#slide-wrap');
    var slides = $('#slide-wrap .slide');
    var index = 1;
    var btnIndex = 0;
    var timer;
    var width = banner[0].offsetWidth;
    var amount = slides.length;
    var animated = false;

    if ( buttons != null ) {
        var button = $('#slide-btns :button');
    };
    //幻灯片切换
    function slideMove(offset){
        var iniLeft = parseInt(list[0].offsetLeft);
        var newLeft = iniLeft + offset;
        var allWidth = -( width * amount );//幻灯片数量
        var time = 300;//位移总时间
        var interval = 10;//位移间隔时间
        var speed = offset / ( time / interval );//每次位移的距离

        function go () {
            var animated = true;
            var oldLeft = parseInt(list[0].offsetLeft);//获取当前left位置
            if ( ( speed < 0 && oldLeft > newLeft ) || ( speed > 0 && oldLeft < newLeft ) ) {
                list.css("left",oldLeft + speed + 'px');
                setTimeout(go,10);
            }else{
                var animated = false;
                list.css("left",newLeft + 'px');
            };
        }
        go();
    }

    //开启自动播放定时器
    function playTime(){
        timer = setInterval(function(){
                    index += 1;
                    var moveWidth = - ( width );
                    if( index > amount ){
                        //小于当前轮播图数量时候
                        moveWidth = width * (amount-1);
                    }
                    showBtn();
                    slideMove(moveWidth);
                }
            ,3000);
    }

    //关闭自动播放定时器
    function stopTime() {
        clearInterval(timer);
    }

    //幻灯片导航切换
    function showBtn(){
        if ( button != null ) {
            var show_btn = $('.slide-btn-af');
            if ( show_btn != null ) {
                show_btn.removeClass('slide-btn-af');
            };
            if ( index < 1 ) {
                index = amount;
            }else if ( index > amount ) {
                index = 1;
            };
            $(button[index - 1]).addClass('slide-btn-af');
        };
    }

    //自动播放运行
    if ( button != null ) {
        for (var i = 0; i < button.length; i++) {
            button[i].onclick = function(){
                if ($(this).hasClass('slide-btn-af')) {
                    return false;
                };
                var myIndex = parseInt(this.getAttribute('index'));
                //要设置的left宽度
                var offset = -( width ) * ( myIndex - index );
                slideMove(offset);
                index = myIndex;
                showBtn();
            }

        };
    };

    //playTime();
})
